package dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.activity_tally;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.mob.wrappers.UMSSDKWrapper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.R;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.activity_login.MD5Utils;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.database.DatabaseHelper;

public class UserActivity extends AppCompatActivity {

    private ListView listView_user;
    private String mData[] = {"修改密码","修改用户名","修改头像","导出账单"};
    private String phoneNumber;
    private DatabaseHelper databaseHelper;
    private SQLiteDatabase sqLiteDatabase;
    private AlertDialog mAlertDialog;
    private AlertDialog.Builder mBuilder;
    private View mView;
    private ImageView icon;
    private Bitmap head;
    private static String path = "/storage/emulated/0/Android/data/dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally/files/Myhead/";
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    protected static final int CROP_SMALL_PICTURE = 2;
    //读写权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //请求状态码
    private static int REQUEST_PERMISSION_CODE = 101;

    private TextView username_user;
    private TextView phone_user;

    EditText etOld;
    EditText etNew1;
    EditText etNew2;
    EditText etUsername;
    Button button_ok;
    Button button_cancel;
    ImageButton back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);

        listView_user = findViewById(R.id.listview_user);
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,mData);
        listView_user.setAdapter(adapter);

        databaseHelper = new DatabaseHelper(UserActivity.this);
        sqLiteDatabase = databaseHelper.getReadableDatabase();

        phoneNumber = getIntent().getStringExtra("phone_toUA");

        username_user = findViewById(R.id.username_user);
        phone_user = findViewById(R.id.phone_user);
        icon = findViewById(R.id.head_portrait);
        back = findViewById(R.id.user_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Bitmap bt = BitmapFactory.decodeFile(path+"head"+phoneNumber+".jpg");
        if(bt != null){
            @SuppressWarnings("deprecation")
            Drawable drawable = new BitmapDrawable(bt);
            icon.setImageDrawable(drawable);
        }
        else{
            /**
             * 如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
             *
             */
        }
        String phoneNumber_hide = phoneNumber.substring(0,3)+"****"+phoneNumber.substring(7,11);
        username_user.setText("用户名："+databaseHelper.getUsername(sqLiteDatabase,phoneNumber));
        phone_user.setText("手机号："+phoneNumber_hide);

        listView_user.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        mBuilder = new AlertDialog.Builder(UserActivity.this);
                        mView = View.inflate(getApplicationContext(),R.layout.dialog_change_password,null);
                        mBuilder.setView(mView);
                        etOld = mView.findViewById(R.id.oldPassword);
                        etNew1 = mView.findViewById(R.id.newPassword1);
                        etNew2 = mView.findViewById(R.id.newPassword2);
                        button_ok = mView.findViewById(R.id.button_ok);
                        button_cancel = mView.findViewById(R.id.button_cancel);
                        button_ok.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String strOld = etOld.getText().toString();
                                String strNew1 = etNew1.getText().toString();
                                String strNew2 = etNew2.getText().toString();
                                if(strOld.equals("") || strNew1.equals("") || strNew2.equals("")){
                                    Toast.makeText(UserActivity.this,"输入框不能为空",Toast.LENGTH_LONG).show();
                                }
                                else if(!strNew1.equals(strNew2)){
                                    Toast.makeText(UserActivity.this,"两次密码输入不一致",Toast.LENGTH_LONG).show();
                                }
                                else if(databaseHelper.getPassword(sqLiteDatabase,phoneNumber).equals(MD5Utils.md5Password(strOld))){
                                        databaseHelper.changePassword(sqLiteDatabase,phoneNumber,MD5Utils.md5Password(strNew1));
                                        Toast.makeText(UserActivity.this,"修改成功",Toast.LENGTH_LONG).show();
                                        mAlertDialog.dismiss();
                                    }
                                else{
                                    Toast.makeText(UserActivity.this,"旧密码输入错误",Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                        button_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mAlertDialog.dismiss();
                            }
                        });
                        mAlertDialog = mBuilder.show();
                        break;
                    case 1:
                        mBuilder = new AlertDialog.Builder(UserActivity.this);
                        mView = View.inflate(getApplicationContext(),R.layout.dialog_change_username,null);
                        mBuilder.setView(mView);
                        etUsername = mView.findViewById(R.id.etUsername);
                        button_ok = mView.findViewById(R.id.button_ok);
                        button_cancel = mView.findViewById(R.id.button_cancel);
                        button_ok.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String strUsername = etUsername.getText().toString();
                                if(databaseHelper.isRegistered(sqLiteDatabase,strUsername)){
                                    Toast.makeText(UserActivity.this,"用户名已注册",Toast.LENGTH_LONG).show();
                                }
                                else{
                                    databaseHelper.changeUsername(sqLiteDatabase,phoneNumber,strUsername);
                                    Toast.makeText(UserActivity.this,"修改成功",Toast.LENGTH_LONG).show();
                                    mAlertDialog.dismiss();
                                    username_user.setText("用户名："+strUsername);
                                }
                            }
                        });
                        button_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mAlertDialog.dismiss();
                            }
                        });
                        mAlertDialog = mBuilder.show();
                        break;
                    case 2:
                        final String[] arrayicon = new String[]{"相机拍照","从手机相册选择"};
                        Dialog alertDialog = new AlertDialog.Builder(UserActivity.this).
                                setItems(arrayicon, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        switch (which){
                                            case 0:
                                                //相机拍照
                                                Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                                intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                                        "head.jpg")));
                                                startActivityForResult(intent2, 2);//采用ForResult打开
                                                break;
                                            case 1:
                                                //从手机相册选择
                                                Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                                                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                                startActivityForResult(intent1, 1);
                                                break;
                                            default:break;
                                        }
                                    }
                                }).create();
                        alertDialog.show();
                        break;
                    case 3:
                        final String arraypath = new String("/storage/emulated/0/Android/data/dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally/files/tally.db");
                        Dialog alertDialog1 = new AlertDialog.Builder(UserActivity.this).
                                setTitle("tally.db").
                                setMessage("路径：\n"+arraypath)
                                .create();
                        alertDialog1.show();
                        break;
                    default:
                        break;
                }
            }
        });
        //权限申请
        int REQUEST_EXTERNAL_STORAGE=1;
        String[] PERMISSIONS_STORAGE={
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        if (PackageManager.PERMISSION_GRANTED!=
                ContextCompat.checkSelfPermission(UserActivity.this, Manifest.permission.WRITE_CONTACTS))
        {
            ActivityCompat.requestPermissions(this,PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
        }

        // android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

    }

    //处理返回的resquestCode
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    cropPhoto(data.getData());//裁剪图片
                }

                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    File temp = new File(Environment.getExternalStorageDirectory()
                            + "/head.jpg");
                    cropPhoto(Uri.fromFile(temp));//裁剪图片
                }

                break;
            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if(head!=null){
                        /**
                         * 上传服务器代码
                         */
                        setPicToView(head);//保存在SD卡中
                        icon.setImageBitmap(head);//显示出来
                    }
                }
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 调用系统的裁剪
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        String fileName =path+"head"+phoneNumber+".jpg";//图片名字


        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}